<?php

namespace adminApi\modules\rbac\controllers;

use adminApi\modules\rbac\models\Adminers;
use adminApi\modules\rbac\models\Permissions;
use adminApi\modules\rbac\models\RoleHasModels;
use adminApi\modules\rbac\models\Roles;
use common\components\fast_api\Controller;
use common\components\wtools\tools\Model;
use common\datas\Enums;
use common\Tools;
use yii\data\ActiveDataProvider;

class RoleController extends Controller
{
    /**
     * 列表
     * @desc 角色列表
     * @param int $page 页码
     * @param int $pageSize 每页条数
     * @param string|null $name 角色名
     * @param string|null $mobile 手机号
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionList($page = 1, $pageSize = 10, $name = null, $status = null)
    {
        $query = Roles::find();
        if ($name) {
            $query->andFilterWhere(['like', 'name', $name]);
        }
        if ($status) {
            $query->andFilterWhere(['status' => $status]);
        }
        $apiPageData = $this->apiPageData($query, $page, $pageSize);
        $items = [];
        foreach ($apiPageData->dataProvider->models as $k => $v) {
            /** @var Roles $v */
            $m = [];
            $m['id'] = $v->id;
            $m['name'] = $v->name;
            $m['created_at'] = $v->created_at;
            $m['_created_at'] = date("Y-m-d H:i", $v->created_at);
            $m['status'] = $v->status;
            $m['_status'] = Enums::getStatusDesc()[$v->status];
            $items[] = $m;
        }
        $data = [
            'items' => $items,
            '_meta' => $apiPageData->meta,
        ];
        return $this->apiSuccess($data, '获取列表成功');
    }

    /**
     * 角色信息
     * @desc 角色详情
     * @param int $id
     * @return array
     */
    public function actionInfo($id)
    {
        $role = Roles::findOne($id);
        $info = [
            'id' => $role->id,
            'name' => $role->name,
            'note' => $role->note,
            'status' => $role->status,
        ];
        $hasPermissions = RoleHasModels::find()
            ->andWhere(['role_id' => $id])
            ->andWhere(['model_type' => RoleHasModels::MODEL_TYPE_PERMISSIONS])
            ->all();
        foreach ($hasPermissions as $k => $v) {
            $permission = Permissions::findOne($v->model_id);
            $info['permissions'][] = $permission->path;
        }
        return $this->apiSuccess([
            'info' => $info,
        ], '获取角色信息成功');
    }

    /**
     * 管理员列表
     * @desc 所有管理员列表
     * @return array all 所有管理员
     * @return array has 角色已拥有的管理员
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionAdminers($role_id = 0)
    {
        $query = Adminers::find()->andWhere(['is_super' => Enums::NO]);
        $all = (clone $query)
            ->select(['id', 'account_name', 'mobile', 'status'])
            ->all();
        $has = [];
        if ($role_id > 0) {
            $roleHasAdminers = RoleHasModels::find()
                ->andWhere(['role_id' => $role_id])
                ->andWhere(['model_type' => RoleHasModels::MODEL_TYPE_ADMINERS])
                ->all();
            foreach ($roleHasAdminers as $k => $v) {
                $has[] = $v->model_id;
            }
        }
        return $this->apiSuccess([
            'all' => $all,
            'has' => $has,
        ], '获取列表成功');
    }

    /**
     * 添加or修改角色
     * @desc post
     * @param string $name
     * @param int $status
     * @param string $note 备注
     * @param string $adminerIds JSON格式，所包含的管理员
     * @param int $id
     * @return array
     */
    public function actionAddOrEdit($name, $status, $note = null, $adminerIds = null, $permissions = null, $id = 0)
    {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            \Yii::$app->db->createCommand("SET SQL_SAFE_UPDATES = 0;")->execute();
            if ($id) {
                $role = Roles::findOne($id);
            } else {
                $role = new Roles();
            }
            $role->name = $name;
            $role->status = $status;
            $role->note = $note;
            if (!$role->save()) {
                throw new \Exception(Model::getModelError($role));
            }
            if ($adminerIds) {
                $adminerIds = Tools::isJson($adminerIds) ?: [];
                $role->syncAdminers($adminerIds);
            }
            if ($permissions) {
                $permissions = Tools::isJson($permissions) ?: [];
                $role->syncPermissions($permissions);
            }
            \Yii::$app->db->createCommand("SET SQL_SAFE_UPDATES = 1;")->execute();
            $trans->commit();
            return $this->apiSuccess();
        } catch (\Exception $e) {
            $trans->rollBack();
            return $this->apiError($e->getMessage());
        }
    }
}
